package com.qingxin.repertory.action;
import java.io.File;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qingxin.park.entity.FarmPark;
import com.qingxin.park.service.FarmParkService;
import com.qingxin.repertory.entity.Repertory;
import com.qingxin.repertory.entity.RepertoryAccount;
import com.qingxin.repertory.service.RepertoryAccountService;
import com.qingxin.repertory.service.RepertoryService;
import com.qingxin.sys.action.BaseAction;
import com.qingxin.sys.mvc.PageParam;
import com.qingxin.sys.mvc.SysError;
import com.qingxin.sys.support.JsTreeNode;
import com.qingxin.sys.utils.ExcelUtil;
import com.qingxin.sys.utils.StringUtils;
import com.qingxin.ui.bean.TreeNode;

/**
 * 库存管理
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/repertory")
public class RepertoryAction extends BaseAction {
	
	@Autowired
	private RepertoryService repertoryService;
	@Autowired
	private RepertoryAccountService  repertoryAccountService;
	
	@Autowired
	private FarmParkService farmParkService;
	
	/**
	 * 加载左侧 园区-库存
	 * @param pid
	 * @return
	 */
	@RequestMapping(value="/lefttree.json", method={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public Object lefttree(String pid, HttpServletRequest request){
		List<TreeNode> rlist = repertoryService.getUITreeData(getLoginUser(request));
		
		List<JsTreeNode> list = new ArrayList<>();
		for(TreeNode treeNode : rlist){
			list.add(new JsTreeNode(treeNode.getId(), treeNode.getName(), "REPERTORY", null,false));
		}
		return list;
	}
	
	/**
	 * 列表
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/list.do", method=RequestMethod.GET)
	public String list(ModelMap model,String pType,String mType, HttpServletRequest request){
		model.put("pType", pType);
		model.put("mType", mType);
		return "/trace/repertory/repertory_list";
	}
	
	/**
	 *  查询 库存数据
	 * @param pageParam
	 * @param search
	 * @param leftdata
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/listdata.json", method={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public Object listdataALL(PageParam pageParam,String pType,String mType,String search,String leftdata,HttpServletRequest request){
		return repertoryService.list(pageParam,pType, mType,search, leftdata, request);
	}
	
	
	
	/**
	 * 作业选择物资使用
	 * @param parkid
	 * @param blockType
	 * @param linkType
	 * @param repertoryid
	 * @param pageParam
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/listSelectData.json", method={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public Object listSelectData(String parkid, String blockType, String linkType, String repertoryid, PageParam pageParam, HttpServletRequest request){
		return repertoryService.listSelectData(parkid, blockType, linkType, pageParam, request);
	}
	
	
	
	/**
	 * 添加 库存信息
	 * @param model
	 * @param leftdata
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/add.do", method=RequestMethod.GET)
	public String add(ModelMap model, String pType,String mType,String leftdata, HttpServletRequest request){
		model.put("parkid", leftdata);
		model.put("pType", pType);
		model.put("mType", mType);
		return "/trace/repertory/repertory_add";
	}
	
	/**
	 * 保存 添加信息
	 * @param repertory
	 * @param result
	 * @param parkid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/save.json", method=RequestMethod.POST)
	@ResponseBody
	public Object save(@Valid Repertory repertory ,BindingResult result, String parkid, HttpServletRequest request){
		if(result.hasErrors()){
			return getSysErrors(result);
		}
		SysError info = repertoryService.add(repertory,parkid,getLoginUser(request), request);
		return info;
	}
	/**
	 * 删除库存信息
	 * @param ids
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/deleteALL.json",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Object deleteALL(String[] repertoryid, HttpServletRequest request){
		return repertoryService.deleteAll(repertoryid,request);
	}
	
	/**
	 * 删除库存信息
	 * @param ids
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/delete.json",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Object delete(String repertoryid, HttpServletRequest request){
		return repertoryService.delete(repertoryid,request);
	}
	
	/**
	 * 更新 库存信息
	 * @param model
	 * @param repertoryid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/edit.do", method=RequestMethod.GET)
	public String edit(ModelMap model, String repertoryid, HttpServletRequest request){
		Repertory repertory = repertoryService.get(repertoryid);
		model.put("repertory", repertory);
		return "trace/repertory/repertory_edit";
	}
	
	/**
	 * 保存修改
	 * @param repertory
	 * @param result
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/update.json", method=RequestMethod.POST)
	@ResponseBody
	public Object update(@Valid Repertory repertory, BindingResult result, HttpServletRequest request){
		if(result.hasErrors()){
			return getSysErrors(result);
		}
		return repertoryService.update(repertory, getLoginUser(request), request);
	}
	
	/**
	 * 流水账列表
	 * @param model
	 * @param repertoryid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/account.do", method=RequestMethod.GET)
	public String account(ModelMap model, String repertoryid, HttpServletRequest request){
		model.put("repertoryid", repertoryid);
		//model.put("accounts", repertoryAccountService.list(repertoryid, request));
		return "trace/repertory/repertory_account2";
	}
	
	/**
	 * 获取流水账 列表数据
	 */
	@RequestMapping(value="/getAccount.json", method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Object getaccount(String repertoryid,PageParam pageParam, HttpServletRequest request){
		
		return repertoryAccountService.list(repertoryid, pageParam, request);

	}
	
	/**
	 * 跳转 添加流水账页面
	 * @param model
	 * @param repertoryid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/addAccount.do", method=RequestMethod.GET)
	public String addaccount(ModelMap model, String repertoryid, HttpServletRequest request){
		Repertory repertory = repertoryService.get(repertoryid);
		model.put("repertory", repertory);
		return "trace/repertory/account_add";
	}
	
	/**
	 * 保存流水账
	 * @param account
	 * @param result
	 * @param repertoryid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/saveAccount.json", method=RequestMethod.POST)
	@ResponseBody
	public Object saveAccount(@Valid RepertoryAccount account ,BindingResult result, String repertoryid, HttpServletRequest request){
		if(result.hasErrors()){
			return getSysErrors(result);
		}
		SysError info = repertoryAccountService.add(account,repertoryid,getLoginUser(request), request);
		return info;
	}
	
	/**
	 * 更新 库存信息
	 * @param model
	 * @param repertoryid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/lookAccount.do", method=RequestMethod.GET)
	public String lookAccount(ModelMap model,String repertoryid, String accountid, HttpServletRequest request){
		Repertory repertory = repertoryService.get(repertoryid);
		RepertoryAccount repertoryAccount = repertoryAccountService.get(accountid);
		model.put("repertory", repertory);
		model.put("repertoryAccount", repertoryAccount);
		return "trace/repertory/account_look";
	}
	
	
	
	/**
	 * 判断农资名称是否存在
	 * @param itemName
	 * @param itemId
	 * @param taskId
	 * @return
	 */
	@RequestMapping(value="/isNameDuplicate.json" , method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public String isNameDuplicate(String materialName, String repertoryid,String productType,String materialType, String parkid){
		boolean existed = repertoryService.isNameDuplicate(materialName,productType,materialType, repertoryid, parkid);
		return existed ? "1":"0";
	}
	
	
	
	/**
	 * 导出Excel
	 * @param model
	 * @param datatype
	 * @param leftdata
	 * @param pType
	 * @param mType
	 * @param search
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/doexport.do", method=RequestMethod.GET)
	public String doexport(ModelMap model, String datatype, String leftdata, String pType, String mType, String search,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		String temps = null;
		String filename = null;
		
		if(StringUtils.isEmpty(leftdata)){
			responseText("参数缺失，缺少园区参数，导出失败。", response);
			return null;
		}
		FarmPark farmPark = farmParkService.get(leftdata);
		if(farmPark == null){
			responseText("参数错误，园区信息无效，导出失败。", response);
			return null;
		}
		
		if("1".equals(pType) && "1".equals(mType)){
			temps = servletContext.getRealPath("/WEB-INF/excelTemps/repertory_seed_export.xlsx");
			filename = farmPark.getParkName()+"-种子信息.xlsx";
		}
		if("1".equals(pType) && "2".equals(mType)){
			temps = servletContext.getRealPath("/WEB-INF/excelTemps/repertory_fertilizer_export.xlsx");
			filename = farmPark.getParkName()+"-化肥信息.xlsx";
		}
		if("1".equals(pType) && "3".equals(mType)){
			temps = servletContext.getRealPath("/WEB-INF/excelTemps/repertory_pesticide_export.xlsx");
			filename = farmPark.getParkName()+"-农药信息.xlsx";
		}
		
		if(StringUtils.isEmpty(temps)){
			responseText("参数错误，数据类型无效，导出失败。", response);
			return null;
		}
		
		File tempsFile = new File(temps);
		if(!tempsFile.isFile()){
			responseText("数据模板文件丢失，导出失败。", response);
			return null;
		}
		
		List<Repertory> list = repertoryService.listForExport(leftdata, pType, mType, search);
		if(list == null){
			list = new ArrayList<Repertory>();
		}
		filename = java.net.URLEncoder.encode(filename, "UTF-8");
		response.resetBuffer();
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment; filename*=utf-8'zh_cn'" + filename);
		
		OutputStream outputStream = response.getOutputStream();
		ExcelUtil.exportExcel(tempsFile, outputStream, list);
		outputStream.close();
		return null;
	}
	
	
	//向响应写入文本
	protected void responseText(String text, HttpServletResponse response) throws Exception {
		response.resetBuffer();
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		out.write("<html><body>");
		out.write("<h2>"+text+"</h2>");
		out.write("</body></html>");
		out.close();
	}
	
	
	
}
